//
//  BKEmotionToolBar.swift
//  微博
//
//  Created by mac on 16/8/19.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

enum BKEmoticonToolBarButtonType: Int{

    case Normal = 0
    case Emoji = 1
    case LXH = 2
}

class BKEmotionToolBar: UIStackView {
    
    //点击toolBar按钮执行的闭包
    var didSelectButtonClosure:((type:BKEmoticonToolBarButtonType)->())?
    
    //记录上一次选中的按钮
    var lastSelectdedButton:UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //水平布局
        axis = .Horizontal
        //等比填充
        distribution = .FillEqually
        
        addChildButton("默认", imageName: "compose_emotion_table_left", buttonType: .Normal)
        addChildButton("Emoji", imageName: "compose_emotion_table_mid", buttonType: .Emoji)
        addChildButton("浪小花", imageName: "compose_emotion_table_right", buttonType: .LXH)
    }
    
    //添加子控件方法
    private func addChildButton (title:String,imageName:String,buttonType:BKEmoticonToolBarButtonType){
    
        let button = UIButton()
        
        //根据枚举的原始值设置tag
        button.tag = buttonType.rawValue
        
        button.setTitle(title, forState: .Normal)
        
        //设置不同状态下文字的颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), forState: .Selected)
        
        //设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        //去掉高亮效果
        //button.adjustsImageWhenHighlighted = false
        
        button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
    
        addArrangedSubview(button)
    }
    
    @objc private func buttonAction(button:UIButton){
        
        if lastSelectdedButton == button {
        
            return
        }
        lastSelectdedButton?.selected = false
        button.selected = true
        
        //保存选中的按钮
        lastSelectdedButton = button
        
        //通过枚举的原始值获取枚举
        let type = BKEmoticonToolBarButtonType(rawValue: button.tag)!
        
        //执行闭包
        didSelectButtonClosure?(type:type)
    }

}
